#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>

#include "materialManager.h"

materialManager* MATM()
{
	return materialManager::instance();
}
materialManager::materialManager()
{
//... perform necessary instance initializations
}
materialManager* materialManager::pinstance = 0;// initialize pointer


materialManager* materialManager::instance()
{
	if (!pinstance)
	{
		pinstance = new materialManager; // create sole instance
	}
	return pinstance; // address of sole instance
}

mat* materialManager::getMaterial(std::string id)
{
	for(int x=0; x<material.size(); x++)
	{
		if(material[x]->name.compare(id) ==0)
			return material[x];
	}
	return 0;
}
float ctoFloat(std::string f)
{
	float fl=0;
	std::stringstream ss;
	ss << f;
	ss >> fl;
	return fl;

}
void message(std::string name)
{
	std::cout << "Material loaded " << name << "\n";
}
bool materialManager::loadMaterial(std::string path)
{
	std::string line="";
	std::ifstream fileIn(path.c_str());
	int step=0;
	mat* m;
	if (fileIn.is_open())
	{
		while (getline (fileIn,line) )
		{
			if (step==0)
			{
				m = new mat();
				m->name = line;
			}
			if (step==1 && line.compare("")!=0)
			{
				//color
			}
			if (step==2 && line.compare("")!=0)
			{//texture
				m->texID = line;
			}
			if (step==3 && line.compare("")!=0)
			{//shader
				m->shaderID = line;
			}
			if (step>3 && line.compare("")!=0)
			{
				//Shader variables
				var* v = new var();
				v->variable = "";
				bool spaceHit=false;
				std::string valueBuf = "";
				for(int x=0; x<line.length(); x++)
				{
					if(line[x] == ' ')
					{
						spaceHit=true; x++;
					}
					if(!spaceHit)
						v->variable += line[x];
					else
						valueBuf+= line[x];
				}
				v->value = ctoFloat(valueBuf);
				m->shaderVariables.push_back(v);
			}
			step++;
			if(line.compare("")==0)
			{
				step=0;
				material.push_back(m);
				message(m->name);
			}
		}
		material.push_back(m); //pushback last one in file
		message(m->name);
	}

	return true;
}


using namespace boost::filesystem; //ALSO CHANGE TO READ LINE INSTEAD OF READ CHARACTER!!!
using namespace std;
void loadMaterialDirectory(const boost::filesystem::path & directory, bool recurse_into_subdirs)
{
    directory_iterator end;

    for( directory_iterator iter(directory) ; iter != end ; ++iter )
    {
        if ( is_directory( *iter ) )
        {
            if( recurse_into_subdirs ) loadMaterialDirectory(*iter, true) ;
        }
        std::stringstream s;
        s << iter->path();
        std::string out; s >> out;
        MATM()->loadMaterial(out);
    }
}